from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True, null=True, blank=True)
    website = models.URLField(blank=True, verify_exists=False)
    feed_url = models.URLField(blank=True, verify_exists=False)
    
    friends = models.ManyToManyField('self')
    
    def __unicode__(self):
        return u"UserProfile for %s" % self.get_display_name()
    
    def get_display_name(self):
        if self.user:
            return unicode(self.user)
        else:
            return self.website
    
    class Admin:
        pass

class CouchDBServerManager(models.Manager):
    def get_url(self):
        cdbs_list = self.get_query_set()
        if cdbs_list.count() == 0:
            cdbs = self.create(url="'http://127.0.0.1:5984")
            return cdbs.url
        else:
            return cdbs_list[0].url

class CouchDBServer(models.Model):
    url = models.URLField()

    objects = CouchDBServerManager()

    def save(self):
        self._default_manager.all().delete()
        super(CouchDBServer, self).save()
    
    class Admin:
        pass

from django.db.models import signals
from django.dispatch import dispatcher

def user_post_save(sender, instance, signal, *args, **kwargs):
    profile, new = UserProfile.objects.get_or_create(user=instance)

dispatcher.connect(user_post_save, signal=signals.post_save, sender=User)
